<?php

class AdvertController extends CController {
   public $isType = 0;
   public $isSmallType = 0;
   public $row = 10;
   public $page = 1;
   public $totalPage = 0;
   public $total = 0;
   
   public $row1 = 10;
   public $page1 = 1;
   public $totalPage1 = 0;
   public $total1 = 0;
   public $layout='application.admin.views.layouts.mainAD';
    public function filters() {
        return array(
            array(
                'application.admin.filters.MemcheckFilter'
            )
        );
    }
    
    protected function _time($time, $model = null) {
        if ($model == 1) {
            return $time - (8 * 3600); //转格林威治时间
        } else if ($model == 2) {
            return $time + (8 * 3600); //转北京时间
        }
     }
     
     public function actionDeleteImgs(){ 
        if(!empty($_POST)){
            $count=0;
            $tar_path='';
            $res=0;
            $aid= array_shift($_POST);
            $namearr=explode(',',$_POST['namearr']);
            foreach ($namearr as $value) {
                $tar_path='upload/ad/'.$aid.'/'.$value;
                $res=$this->delete_file($tar_path);
                $count+=$res;
            }            
        }
        echo $count;
     }
     public function actionDeleteImg(){
        $tar_path='upload/ad/'.$_POST['aid'].'/'.$_POST['oldname'];               
        $res=$this->delete_file($tar_path);
        echo $res;
     }
     private function delete_file($fullpath){         
        if (is_file($fullpath)) {              
                    unlink($fullpath);
                    return 1;
         }else {
             return 0;
         }
     }

    private function deldir($dir) {
        //先删除目录下的文件：
        $dh = opendir($dir);
        while ($file = readdir($dh)) {
            if ($file != "." && $file != "..") {
                $fullpath = $dir . "/" . $file;
                if (!is_dir($fullpath)) {
                    unlink($fullpath);
                } else {
                    $this->deldir($fullpath);
                }
            }
        }
        closedir($dh);
        if (rmdir($dir)) {
            return true;
        } else {
            return false;
        }
    }

     public function actionIndex() {
        $this->page = isset($_GET['page'])&&!empty($_GET['page'])?$_GET['page']:1;
        $this->isType = 3;
        $this->isSmallType = $_GET['isSmallType'];
        $DTad_arr=array();        
        $limit = ' limit '.(($this->page-1)*$this->row).','.$this->row;
        $where = adminSys::_whereWork($_POST);
        $sql = 'select * from {{ad}} '.$where.$limit;
        $sql1 = 'select count(*) as count_num from {{ad}} '.$where;
        $DTad_arr = Yii::app()->db->createCommand($sql)->queryAll();
        $DTad_arr_count = Yii::app()->db->createCommand($sql1)->queryAll();
        $this->totalPage = ceil($DTad_arr_count[0]['count_num']/$this->row);
        $this->total = $DTad_arr_count[0]['count_num'];
        $this->render('AD_Ctrl',array(              //局部渲染
            'AD_arr'=>$DTad_arr,
            'AD_info_arr'=>$DTad_info_arr
        )); 
    }
    

    
    public function actionADinsert(){
         $exists= Ad::model()->exists("aid=:_aid",array(":_aid"=>$_POST['aid']));
        if($exists){ 
             $res=$this->ADupdate($_POST);
            if($res){               
                echo -1;    
            }else{              
                echo 0;
            }
            return;
        }
            $DTad = new Ad();
            $DTad->title=$_POST['title'];
            $DTad->width=(int)$_POST['width'];
            $DTad->height=(int)$_POST['height'];
            $DTad->ismobile=(int)$_POST['ismobile'];
            $DTad->Stime=(int)$this->_time(time(),1);            
            $DTad->save();
            echo (int)$DTad->aid;                   
    }
    public function actionADdelete(){   
        $ADpath=dirname(Yii::app()->BasePath).'/upload/ad/'.$_POST['aid'];        
        if(is_dir($ADpath)){
           if($this->deldir($ADpath)){                          
               $count1 = Ad_info::model()->deleteAll(' aid=:_aid ',array(':_aid'=>$_POST['aid']));                              
           }
        }
        $count = Ad::model()->deleteByPk($_POST['aid']);
        echo $count;        
    }
    private function ADupdate($post){
        if(!empty($post)){
            $tar_AD = Ad::model()->findByPk($post['aid']);            
            if($tar_AD->title != $post['title'] && !empty($post['title']) && $post['title'] != 'undefined'){$tar_AD->title = $post['title'];}
            if($tar_AD->width != $post['width'] && !empty($post['width']) && $post['width'] != 'undefined'){$tar_AD->width = $post['width'];}
            if($tar_AD->height != $post['height'] && !empty($post['height']) && $post['height'] != 'undefined'){$tar_AD->height = $post['height'];}
            if($tar_AD->ismobile != $post['ismobile'] && !empty($post['ismobile']) && $post['ismobile'] != 'undefined'){$tar_AD->ismobile = $post['ismobile'];}            
            $tar_AD->update();  
            $bak=$tar_AD->aid;            
            return $bak;
        }        
        else{
            return false;
        }
    }
    public function actionADupdate(){
        if(!empty($_POST)){
            $tar_aid=$this->ADupdate($_POST);
           if($tar_aid){
               echo $tar_aid;
           }
        }        
        else{
            echo 0 ;          
        }
    }
    public function actionADinfoinsert(){
         $exists= Ad_info::model()->exists("title=:_name",array(":_name"=>$_POST['title']));
        if($exists){            
            $_POST['title']=$_POST['title'].'_c';
        }
            if($this->ADinfoInsert($_POST)){
                echo 1;        
            }else{
                echo 0;
            }
    }
    private function ADinfoInsert($data){
        
        if(!empty($data)){
              try {
                $DTadinfo = new Ad_info();
                $DTadinfo->aid=$data['aid'];
                $DTadinfo->title=$data['title'];
                $DTadinfo->url='/';
                $DTadinfo->imgpath=$data['imgpath'];
                $DTadinfo->ordering=0;
                $DTadinfo->Stime=(int)$this->_time(time(),1);            
                $DTadinfo->save();                 
                return true;
              } catch (Exception $exc) {
                  echo $exc->getTraceAsString();
                  return false;
              }

        }
         
    }
    public function actionInsertbyQueue(){
        if(!empty($_POST)){
            $aid=0;
            $inCount=0;
            if(!empty($_POST['aid'])){
                $aid=$_POST['aid'];
                array_shift($_POST);}  
            foreach ($_POST as $key => $value) { 
                $arr=array();
                $arr['aid']=$aid;
                $fileimg=explode("-",$value);
                $varr=explode(".",$value);
                $arrext=explode("-",$varr[1]);                                        
                $title=$varr[0];
                if(!empty($arrext[1])){
                    $title=$arrext[1];
                }
                $arr['title']=$title;
                $arr['url']='/';
                
                $arr['imgpath']='ad/'.$aid.'/'.$fileimg[0];
                if($this->ADinfoInsert($arr)){
                    $inCount++;
                    continue;
                }else{
                    break;
                }                
            }  
            echo $inCount;
        }
    }
    public function actionADinfodelete(){
        $ADinfopath=dirname(Yii::app()->BasePath).'/upload/'.$_POST['imgpath'];
        if(is_file($ADinfopath)){
           if(unlink($ADinfopath)){
               $count = Ad_info::model()->deleteByPk($_POST['id']);   
               echo $count;    
           }
        }
        return 0;    
    }
    public function actionADinfoSaveOrd(){
        $count=0;
        if(!empty($_POST)){
            $count=0;            
            $arr=array();
            foreach ($_POST as $key => $value){
                $arr['id']=$key;
                $arr['ordering']=(int)$value;
                $count=$count+$this->ADinfoupdate($arr);                    
            }
        }
        echo $count;
    }
    private function ADinfoupdate($post){
        if(!empty($post)){
            $tar_ADinfo = Ad_info::model()->findByPk($post['id']);
            if($tar_ADinfo->title != $post['title'] && !empty($post['title']) && $post['title'] != 'undefined'){echo 'title modify';$tar_ADinfo->title = $post['title'];}
            if($tar_ADinfo->imgpath != $post['imgpath'] && !empty($post['imgpath']) && $post['imgpath'] != 'undefined'){echo 'title modify';$tar_ADinfo->imgpath = $post['imgpath'];}
            if($tar_ADinfo->ordering != $post['ordering'] && !empty($post['ordering']) && $post['ordering'] != 'undefined'){echo 'title modify'; $tar_ADinfo->ordering = $post['ordering'];}
            $bak = $tar_ADinfo->update();            
            return $bak;
        }        
        else{
            return 0;
        }
    }
    public function actionADinfoupdate(){  
        if(!empty($_POST)){
            $tar_ADinfo = Ad_info::model()->findByPk($_POST['id']);
            if($tar_ADinfo->title != $_POST['title'] && !empty($_POST['title']) && $_POST['title'] != 'undefined'){$tar_ADinfo->title = $_POST['title'];}
            if($tar_ADinfo->imgpath != $_POST['imgpath'] && !empty($_POST['imgpath']) && $_POST['imgpath'] != 'undefined'){$tar_ADinfo->imgpath = $_POST['imgpath'];}
            if($tar_ADinfo->ordering != $_POST['ordering'] && !empty($_POST['ordering']) && $_POST['ordering'] != 'undefined'){$tar_ADinfo->ordering = $_POST['ordering'];}
            $bak = $tar_ADinfo->update();
            echo $bak;
        }        
        else{
            echo false;
        }
    }
    public function actionADinfo(){
        //--------------
        $show_mod=$_GET['mod'];
        $data = array();
        $DTad_info_arr=array();
        $this->layout='application.admin.views.layouts.main';
        $this->isType = 3;
        $this->isSmallType = $_GET['isSmallType'];
        if($show_mod==2){
           $this->page1 = isset($_GET['page'])?$_GET['page']:1;
           $limit = ' limit '.(($this->page1-1)*$this->row1).','.$this->row1;   
           $where = adminSys::_whereWork($_GET);
           $sql = 'select * from {{ad_info}} '.$where.'ORDER BY {{ad_info}}.ordering'.$limit;
           $sql1 = 'select count(*) as count_num from {{ad_info}} '.$where;           
           $data[0] = Yii::app()->db->createCommand($sql)->queryAll();
           $data[1] = Yii::app()->db->createCommand($sql1)->queryAll();
           $this->totalPage1 = ceil($data[1][0]['count_num']/$this->row1);
           $this->total1 = $data[1][0]['count_num'];
           $DTad_info_arr = $data[0];
        }       
        $this->render('ADinfo_Ctrl',array(              //局部渲染         
            'AD_info_arr'=>$DTad_info_arr,
            'ADname'=>$_GET['ADname'],
            'ADwidth'=>$_GET['ADwidth'],
            'ADheight'=>$_GET['ADheight'],
            'ADismobile'=>$_GET['ADismobile'],
            'ADStime'=>$_GET['ADStime'],
            'show_mod'=>$show_mod,
            'aid'=>$_GET['aId']
        ));
        
        
    }

    

    public function actionAdvertEdit(){
        if($_GET['mod']==2){ 
            if(empty($_GET['id']))$this->redirect (array('site/error','msg'=>'ID不能为空！'));
            $data = Ad_info::model()->findByPk($_GET['id']);
        }        
        $this->render('advertEdit',array(
            'data'=>$data,
            'title'=>'编辑图片信息',
            'id'=>$_GET['id'],
            'AD_name'=>$_GET['ADname'],
            'show_mod'=>$_GET['mod'],
            'aid'=>$_GET['aid']
        ));
    }

}

